package com.yunduo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunduo.common.YunDuoConst.FileType;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.PFile;
import com.yunduo.entity.vo.FileObj;
import com.yunduo.handler.exceptionhandler.OperationException;
import com.yunduo.service.PFileService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件控制类
 */
@RestController
public class PFileController {

    @Resource
    private PFileService pFileService;
    //查找文件
    @GetMapping("/PFile")
    public CommonReturn getFile(String id){
        PFile file = pFileService.getById(id);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("file",file);
    }

    //上传文件
    //前端使用formdata对象
    // 文件 和 文件名上传
    @PostMapping("/PFile/up")
    public CommonReturn uploadFile(@RequestParam("file") MultipartFile file){
        if(null == file){
            return CommonReturn.ERROR(ResultCode.ERROR).setMessage("文件为空");
        }
        PFile data;
        FileObj fileObj = new FileObj();
        try {
            fileObj.setData(file.getBytes());
            fileObj.setName(file.getOriginalFilename());
            fileObj.setType(YunDuoUtils.checkFileType(file.getOriginalFilename()));
            data = pFileService.uploadFile(fileObj);
        } catch (IOException e) {
            throw new OperationException(ResultCode.ERROR.getCode(),"文件上传失败");
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("file",data);
    }

    //删除文件
    @DeleteMapping("/PFile/delete")
    public CommonReturn deleteFile(@RequestBody String url){
        if(url == null || StringUtils.isEmpty(url)){
            return CommonReturn.SUCCESS(ResultCode.SUCCESS);
        }
        LambdaQueryWrapper<PFile> fileLambdaQueryWrapper = new LambdaQueryWrapper<>();
        fileLambdaQueryWrapper.eq(PFile::getUrl,url);
        PFile file = pFileService.getOne(fileLambdaQueryWrapper);
        if(null == file){
            return CommonReturn.SUCCESS(ResultCode.SUCCESS);
        }
        FileObj fileObj = new FileObj();
        fileObj.setId(file.getId());
        fileObj.setType(YunDuoUtils.checkFileType(url));
        fileObj.setName(file.getName());
        pFileService.removeFile(fileObj);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //下载文件
    @GetMapping("/PFile/{id}")
    public CommonReturn downLoadFile(@PathVariable String id, HttpServletResponse response){
        FileObj fileObj = createFileObj(id);
        InputStream inputStream = pFileService.downloadFile(fileObj);
        byte[] data = new byte[1024];
        try {
            while (inputStream.read(data) != -1) {
                response.getOutputStream().write(data);
            }
        } catch (Exception e) {
            throw new OperationException(ResultCode.ERROR.getCode(),"文件下载失败");
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //封装对具体文件进行操作的对象
    private FileObj createFileObj(String id){
        PFile file = pFileService.getById(id);
        FileType fileName = YunDuoUtils.checkFileType(file.getName());
        FileObj fileObj = new FileObj();
        fileObj.setId(id);
        fileObj.setName(file.getName());
        fileObj.setType(fileName);
        return fileObj;
    }
}
